package com.spark.trouble.agency

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.google.gson.Gson
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.RejectAlert
import com.spark.trouble.R
import com.spark.trouble.SpotHanAgencyInfoModel
import kotlinx.android.synthetic.main.frag_punish_scheme.*

/**
 * 待办 -> 现场治理 -> 待审核 -> 处罚方案
 */
class PunishSchemaFragment : BaseFragment() {
    private var taskId = ""

    companion object {
        fun newInstance(taskId: String): PunishSchemaFragment {
            val target = PunishSchemaFragment()
            val args = Bundle()
            args.putString("taskId", taskId)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_punish_scheme
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        arguments?.apply {
            getString("taskId")?.apply {
                this@PunishSchemaFragment.taskId = this
                fetchInfo(this)
            }
        }
        // 驳回
        tv_reject.setOnClickListener {
            activity?.apply {
                RejectAlert.Builder(this, "驳回理由", "请输入驳回理由")
                        .affirm { d, str ->
                            if (str.isNullOrBlank())
                                alert("请输入驳回理由")
                            else {
                                d.dismiss()
                                submitAgencyRejctVerify(this@PunishSchemaFragment.taskId, str!!)
                            }
                        }
                        .cancel { d, i ->
                            d.dismiss()
                        }
                        .create()
                        .show()
            }
        }
        // 通过
        btn_resolve.setOnClickListener { submitAgencyVerify(taskId) }
    }

    /**
     * restore state
     */
    @SuppressLint("SetTextI18n")
    private fun restore(
            lostPoint: String,
            fine: String,
            htLevel: String,
            leader: String,
            respUnit: String,
            respMan: String,
            acceptMan: String
    ) {
        tv_lost_point.text = "${lostPoint}分"
        tv_fine.text = "${fine}元"
        tv_ht_level.text = htLevel
        tv_leader.text = leader
        tv_resp_unit.text = respUnit
        tv_resp_man.text = respMan
        tv_accept_man.text = acceptMan
    }

    /**
     * [待办] 待审核
     * */
    @SuppressLint("CheckResult")
    private fun fetchInfo(taskId: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_spot_fetch_verify}", mutableMapOf("taskId" to taskId).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, SpotHanAgencyInfoModel::class.java)?.apply {
                                if (code == "200" && resultMaps.isNotEmpty()) {
                                    resultMaps[0].apply {
                                        restore(
                                                responsible_score.toString(),
                                                responsible_money.toString(),
                                                trouble_level,
                                                responsible_leader_name,
                                                responsible_department_name,
                                                responsible_user_name,
                                                acceptor_name)
                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )
    }

    /**
     * [待办] 待审核
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyVerify(taskId: String) {
        val params = mutableMapOf("taskId" to taskId, "approveState" to "2")
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_spot_submit_verify}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else
                                    error("提交失败")
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }

    /**
     * [待办] -> 待审核 -> 驳回
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyRejctVerify(taskId: String, rejectReason: String) {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_alltask_submit_reject2_verify_confirm}", mutableMapOf("taskId" to taskId, "refuseReason" to rejectReason).toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }
}